﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Utils.Http
{
    public class DefaultHttpHandler : DelegatingHandler
    {
        static DefaultHttpHandler()
        {
            EncodingProvider provider = CodePagesEncodingProvider.Instance;
            Encoding.RegisterProvider(provider);
        }

        public DefaultHttpHandler()
        {

            this.InnerHandler = new HttpClientHandler
            {
                AllowAutoRedirect = true,
                UseCookies = true,
                AutomaticDecompression = System.Net.DecompressionMethods.GZip,
                ClientCertificateOptions = ClientCertificateOption.Automatic
            };
        }

        public CookieContainer GetCookieContainer()
        {
            return ((HttpClientHandler)this.InnerHandler).CookieContainer;
        }

        public DefaultHttpHandler(HttpClientHandler handler)
        {
            this.InnerHandler = handler;
        }

        protected virtual IDictionary<string, string> GetHeaders()
        {
            IDictionary<string, string> headers = new Dictionary<string, string>();
            headers.Add("Accept", "text/html,application/xhtml+xml,application/xm,application/json");
            headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36");
            return headers;
        }

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            foreach (var item in GetHeaders())
            {
                request.Headers.Add(item.Key, item.Value);
            }
            return base.SendAsync(request, cancellationToken);
        }
    }
}
